package com.jpcc.vw.onlineRadio.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;

import com.cns.android.account.CnsAccountInfo;
import com.cns.android.datacollect.DataCollectManager;
import com.cns.android.media.MediaInfoManager;
import com.danikula.videocache.HttpProxyCacheServer;
import com.google.gson.Gson;
import com.jpcc.onlineradio.recycle.CustomClassicsFooter;
import com.jpcc.vw.onlineRadio.activity.MainActivity;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.action.CountAction;
import com.jpcc.vw.onlineRadio.model.action.RadioCountAction;
import com.jpcc.vw.onlineRadio.model.action.RequestFocusRefreshAction;
import com.jpcc.vw.onlineRadio.model.bean.CnsAccountInfoSelf;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.service.PlayAlbumRadioService;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.liulishuo.filedownloader.FileDownloader;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;

/*Start by menglingqiang*/
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.jpcc.vw.tracelog.TracelogInterface;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.zhy.http.okhttp.callback.FileCallBack;
//import java.io.File;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
/*End by menglingqiang*/
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


/**
 * 自定义Application
 * Created by wcy on 2015/11/27.
 */
public class MusicApplication extends Application {

    public static MusicApplication instance;
    /*Start by menglingqiang*/
    private final static String TAG = "Radio";
    /*End by menglingqiang*/
    private RefWatcher refWatcher;
    /**
     * 打开的activity
     **/
    private List<Activity> activities = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        AppCache.get().init(this);
//        refWatcher = setupLeakCanary();
//        initLeakCanary();
        initSmartRefreshLayoutHeaderFooter();
        ForegroundObserver.init(this);
        EventBus.getDefault().register(this);
        ToastUtils.init(this);
        FileDownloader.init(this);
        //必须调用初始化
        OkHttpUtils.init(this);
        DownloadManager.getInstance(this).setTargetFolder(Environment.getExternalStorageDirectory() + "/OnlineRadio" + "/track/");
//        OkGo.getInstance().init(this);
//        OkDownload.getInstance().setFolder(TrackUtils.getTrackDir());
//        OkDownload.getInstance().getThreadPool().setCorePoolSize(1);

//        QuietDownloader.getImpl().bindService(this);
//        QuietConfigs.getImpl()
//                .initDownloadFile(new File(Environment.getExternalStorageDirectory() + "/OnlineRadio"+ "/track/"))
//                .setMaxDownloadTasks(5)
//                .setMaxRetryCount(3)
//                .setHandlerNetworkListener(new QuietConfigs.HandlerNetworkListener() {
//                    @Override
//                    public boolean onHandlerNetworkStatus() {
//                        return false;
//                    }
//                });
        //Add by JPCC
        bindTraceLogService();

        reconnectThread = new Thread() {
            @Override
            public void run() {
                while (needReconnect) {
                    try {
                        Log.d(TAG, "reconnecting to tracelogservice...");
                        Thread.sleep(10000);
                        //Reconnect
                        bindTraceLogService();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }
        };
    }

    private RefWatcher setupLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(this);//1
    }

    public static RefWatcher getRefWatcher(Context context) {
        MusicApplication leakApplication = (MusicApplication) context.getApplicationContext();
        return leakApplication.refWatcher;
    }


    private void initLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        //add by JPCC
        this.unbindService(conn);
    }

    public static MusicApplication GetInstance() {
        synchronized (MusicApplication.class) {
            if (instance == null) {
                instance = new MusicApplication();
            }
        }
        return instance;
    }

    /*Add by menglingqiang*/
    //TestThread thread;

    public boolean running = true;

    Thread reconnectThread;
    public boolean needReconnect = true;

    public static TracelogInterface getLogInterface() {
        return logInterface;
    }
    //private static TracelogInterface logInterface;

    //AIDL
    private static TracelogInterface logInterface;
    ServiceConnection conn;

    public void bindTraceLogService() {
        Log.d(TAG, "bindTraceLogService");
        boolean isBinded = false;
        Intent intent = new Intent();
        intent.setAction("com.jpcc.vw.tracelog.Service.TraceLogService");
        //表示按照什么进行过滤，启动意图
        /*android5.0之后，如果servicer不在同一个App的包中，需要设置service所在程序的包名（包名可以到App的清单文件AndroidManifest中查看）*/
        intent.setPackage("com.jpcc.vw.tracelog");
        //Bind Service

        conn = new ServiceConnection() {
            //绑定成功回调
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d(TAG, "onServiceConnected");
                logInterface = TracelogInterface.Stub.asInterface(iBinder);
                try {
                    // 注册死亡代理
                    iBinder.linkToDeath(mDeathRecipient, 0);
                    // Stop reconnect thread
                    needReconnect = false;
                    // Run test thread
                    running = true;
                    //thread = new TestThread();
                    //thread.run();

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
            }
        };

        this.bindService(intent, conn, BIND_AUTO_CREATE);
    }

    public TracelogInterface getInterface() {
        return logInterface;
    }

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        // 当绑定的service异常断开连接后，会自动执行此方法
        @Override
        public void binderDied() {
            Log.e(TAG, "enter Service binderDied ");
            running = false;
            if (logInterface != null) {
                logInterface.asBinder().unlinkToDeath(mDeathRecipient, 0);
                // Stop test thread
                running = false;

                // 重新绑定服务端的service
                needReconnect = true;
                reconnectThread.start();
            }
        }
    };


    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        MusicApplication app = (MusicApplication) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
//        return new HttpProxyCacheServer(this);


//        String cacheDirectory = Constants.CACHE_DIRECTORY + File.separator + GetUserId() + File.separator;
//
//        File file = new File(Environment.getExternalStorageDirectory(), cacheDirectory);
//        if (!file.exists()) {
//            file.mkdirs();
//        }


        return new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .build();
    }


    private void initSmartRefreshLayoutHeaderFooter() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(android.R.color.transparent, android.R.color.transparent);//全局设置主题颜色
                //return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);//指定为经典Header，默认是 贝塞尔雷达Header
                return new MaterialHeader(context);
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new CustomClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
                //return new footer
            }
        });
    }

    public static long GetUserId() {
        if (Constants.isRelease) {
            if (TextUtils.isEmpty(PreferenceUtils.GetAccountInfo())) {
                return 123456;
            } else {
                CnsAccountInfoSelf accountInfo = new Gson().fromJson(PreferenceUtils.GetAccountInfo(), CnsAccountInfoSelf.class);
                if (TextUtils.isEmpty(accountInfo.getId())) {
                    return 123456;
                } else {
                    if (isInteger(accountInfo.getId())) {
                        return Long.parseLong(accountInfo.getId());
                    } else {
                        return 123456;
                    }
                }
            }
        } else {
//            isInteger("1471251471104114688");
//            return Long.parseLong("1471251471104114688");
            return 123456;
        }
    }

    /*方法二：推荐，速度最快
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public String GetToken() {
        String token = "";
//        try {
//            token= AppTokenManager.getInstance(this).getAuthToken("").getToken();
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
        return "testToken";
    }


    public void onEvent(RadioCountAction action) {
        if (action != null) {
            CountAction actionCount = new CountAction();
            actionCount.setDatatype("others");
            actionCount.setDatacontenttype(128);
            String dataContent = new Gson().toJson(action);
            actionCount.setDatacontent(dataContent.replace("{", "").replace("}", ""));
            actionCount.setDatalength(actionCount.getDatalength());
            String resultJson = new Gson().toJson(actionCount);
//            resultJson.replace("{","");
//            resultJson.replace("}","");
//            String returnJson=resultJson.replace("{","").replace("}","");
            try {
                if (Constants.isRelease) {
                    DataCollectManager.getInstance(this).sendMessage(resultJson);
                }
                Logger.i("sendMessage-->" + resultJson);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void onEvent(RequestFocusRefreshAction action) {
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            Logger.i("enter event");
            Bundle bundle = new Bundle();
            bundle.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
            bundle.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
            bundle.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
            bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
            if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                bundle.putString("radio_type", "album");
            } else {
                bundle.putString("radio_type", "radio");
            }
            bundle.putString(MediaInfoManager.KEY_GENRE, "");


            String CoverEndType = ".jpg";
            if ((!TextUtils.isEmpty(AlbumRadioAudioPlayer.get().getPlayMusic().getCover()))) {
                if (AlbumRadioAudioPlayer.get().getPlayMusic().getCover().contains("png")) {
                    CoverEndType = ".jpg";
                } else {
                    CoverEndType = ".jpg";
                }
            }


//            File directory = new File("/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + AlbumRadioAudioPlayer.get().getPlayMusic().getCover().substring(AlbumRadioAudioPlayer.get().getPlayMusic().getCover().lastIndexOf(".")));

            File directory = new File("/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
            if (directory.exists()) {
                directory.delete();
            }

            if (Constants.isRelease) {
                if (!directory.exists()) {
                    RecentAlbumRadioTrackBean radio = AlbumRadioAudioPlayer.get().getPlayMusic();
                    if ((!TextUtils.isEmpty(radio.getCover())) && (radio.getCover().length() > 3)) {
                        Logger.i("MusicApplication getCover()---->" + radio.getCover());
                        Logger.i("MusicApplication File path---->" + "/mnt/tmpnfs/onlinecovericons/radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                        com.zhy.http.okhttp.OkHttpUtils
                                .get()
                                .url(radio.getCover())//
                                .build().execute(new FileCallBack("/mnt/tmpnfs/onlinecovericons", "radio_" + radio.getTrackId() + "_icon" + CoverEndType) {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Logger.i("download error---->" + e.toString());
                                directory.deleteOnExit();
                            }

                            @Override
                            public void onResponse(File response, int id) {
                                response.setWritable(true, false);
                                response.setReadable(true, false);
                                Bundle bundleLocal = new Bundle();
                                bundleLocal.putString("album", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());

                                bundleLocal.putString("artist", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
                                bundleLocal.putString("title", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());


                                String CoverEndType = ".jpg";
                                if ((!TextUtils.isEmpty(radio.getCover()))) {
                                    if (radio.getCover().contains("png")) {
                                        CoverEndType = ".jpg";
                                    } else {
                                        CoverEndType = ".jpg";
                                    }
                                }


//                                bundle.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
                                Logger.i("MusicApplication RadioCoverFile cover download success---->" + "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                                bundleLocal.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/" + "radio_" + radio.getTrackId() + "_icon" + CoverEndType);
                                bundleLocal.putString("radio_id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
                                if ("album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                                    bundleLocal.putString("radio_type", "album");
                                } else {
                                    bundleLocal.putString("radio_type", "radio");
                                }
                                bundleLocal.putString(MediaInfoManager.KEY_GENRE, "");
                                try {
                                    if (Constants.isRelease) {
                                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendMediaInfo(bundleLocal);
                                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendMediaInfo(bundleLocal);
                                        if (AlbumRadioAudioPlayer.get().isPlaying()) {
                                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                                        } else {
                                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                                        }
                                    }
                                    Logger.i("MusicApplication sendMediaInfo----->" + bundleLocal.toString());

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Logger.i("exception-->" + e.toString());
                                }
                            }
                        });
                    }
                } else {
                    try {
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                        bundle.putString("album_cover_uri", "/mnt/tmpnfs/onlinecovericons/radio_" + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "_icon" + CoverEndType);
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendMediaInfo(bundle);


                        Logger.i("album-->" + bundle.getString("album"));
                        Logger.i("artist-->" + bundle.getString("artist"));
                        Logger.i("title-->" + bundle.getString("title"));
                        Logger.i("radio_id-->" + bundle.getString("radio_id"));
                        Logger.i("radio_type-->" + bundle.getString("radio_type"));
                        Logger.i("album_cover_uri-->", bundle.getString("album_cover_uri"));


                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendMediaInfo(bundle);
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                        if (AlbumRadioAudioPlayer.get().isPlaying()) {
                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PLAYING);
                        } else {
                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                        Logger.i("exception-->" + e.toString());
                    }
                }
            }
        } else {
            Logger.i("enter event empty");
            Bundle bundle = new Bundle();
            bundle.putString("album", "");
            bundle.putString("artist", "");
            bundle.putString("title", "");
            bundle.putString("radio_id", "");
            bundle.putString("radio_type", "album");
            bundle.putString(MediaInfoManager.KEY_GENRE, "");
            bundle.putString("album_cover_uri", "");
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendMediaInfo(bundle);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendPlayStatus(MediaInfoManager.PLAY_STATUS_PAUSED);
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

    }


    /**
     * 新建了一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    public void finishOtherActivities() {
        List<Activity> localActivities = new ArrayList<>();
        if (activities != null && activities.size() > 0) {
            for (Activity activity : activities) {
                if (activity != null) {
                    if (!activity.getClass().getName().equals(MainActivity.class.getName())) {
//                        this.activities.remove(activity);
                        activity.finish();
                    } else {
                        localActivities.add(activity);
                    }
                }
            }
            activities.clear();
            activities.addAll(localActivities);
        }
    }

    /**
     * 结束指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            this.activities.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    public int getActivityNum() {
        if (activities != null) {
            return activities.size();
        }
        return 0;
    }
}
